package com.cicc.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cicc.springboot.common.dto.R;
import com.cicc.springboot.entity.SrmSupplierBasicEntity;
import com.cicc.springboot.mapper.SupplierMapper;

import com.cicc.springboot.model.SupplierQuery;
import com.cicc.springboot.service.SupplierService;
import com.cicc.springboot.utile.OrderNumberGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import java.util.stream.Collectors;

/**
 * Author: 张月鹿
 */

@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, SrmSupplierBasicEntity> implements SupplierService {

    @Autowired
    private SupplierMapper supplierMapper;

    /**
     * 模糊查询+分页功能
     *
     * @param supplierName
     * @param erpCode
     * @param tenantState
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public R<Page<SupplierQuery>> searchSuppliers(String supplierName, String erpCode, String tenantState, int currentPage, int pageSize) {

        // 创建 QueryWrapper 用于数据库字段模糊查询
        QueryWrapper<SrmSupplierBasicEntity> queryWrapper = new QueryWrapper<>();
        if (supplierName != null && !supplierName.isEmpty()) {
            queryWrapper.like("supplier_name", supplierName);
        }
        if (erpCode != null && !erpCode.isEmpty()) {
            queryWrapper.like("erp_code", erpCode);
        }
        if (tenantState != null && !tenantState.isEmpty()) {
            queryWrapper.like("tenant_state", tenantState);
        }
        // 创建分页对象，用于分页查询
        Page<SrmSupplierBasicEntity> supplierPage = new Page<>(currentPage, pageSize);

        // 使用 this.page 方法进行分页查询
        Page<SrmSupplierBasicEntity> resultPage = this.page(supplierPage, queryWrapper);


        List<SupplierQuery> supplierQueries = resultPage.getRecords().stream().map(supplier -> {
            SupplierQuery supplierQuery = new SupplierQuery();
            // 将 SrmSupplierBasicEntity 的字段复制到 SupplierQuery
            BeanUtils.copyProperties(supplier, supplierQuery);
            // 拼接地址字段
            String concatenatedAddress = (supplierQuery.getCountry() == null ? "" : supplierQuery.getCountry().trim()) +
                    (supplierQuery.getProvince() == null ? "" : supplierQuery.getProvince().trim()) +
                    (supplierQuery.getCity() == null ? "" : supplierQuery.getCity().trim()) +
                    (supplierQuery.getStreetSign() == null ? "" : supplierQuery.getStreetSign().trim());
            supplierQuery.setAddress(concatenatedAddress.trim()); // 设置拼接后的地址
            return supplierQuery;
        }).collect(Collectors.toList());


        Page<SupplierQuery> supplierQueryPage = new Page<>(currentPage, pageSize);
        supplierQueryPage.setTotal(resultPage.getTotal());     // 设置总记录数
        supplierQueryPage.setPages(resultPage.getPages());     // 设置总页数
        supplierQueryPage.setCurrent(resultPage.getCurrent()); // 设置当前页数
        supplierQueryPage.setSize(resultPage.getSize());       // 设置每页大小
        System.out.println("输出：" + supplierQueryPage.getPages() + ":" + resultPage.getCurrent());
        supplierQueryPage.setRecords(supplierQueries);

        // 返回查询结果
        return R.ok(supplierQueryPage, "查询成功");
    }

    /**
     * 添加供应商
     *
     * @param supplierQuery 供应商查询对象，包含供应商的相关信息
     * @return 返回操作结果，包括供应商添加成功或失败的信息
     */
    @Override
    public R<SrmSupplierBasicEntity> addSuppliers(SupplierQuery supplierQuery) {
        //  生成新的供应商 ID
        String newSupplierId = OrderNumberGenerator.generateOrderNumber();
        supplierQuery.setErpCode(newSupplierId);

        System.out.println("有没有数据" + supplierQuery);
        //  保存新供应商
        boolean saveResult = save(supplierQuery);
        return saveResult ? R.ok(supplierQuery, "供应商添加成功") : R.failed("供应商添加失败");
    }

    /**
     * @param id 要删除的供应商的 ID
     * @return 返回删除操作的结果，true 表示删除成功，false 表示删除失败
     */
    @Override
    public R<SrmSupplierBasicEntity> deleteUserById(Long id) {
        // 查询id是否存在
        SrmSupplierBasicEntity supplier = supplierMapper.selectById(id);
        if (supplier == null) {
            return R.failed("不存在此条数据");
        }
        boolean deleteResult = this.removeById(id);
        return deleteResult ? R.ok(supplier, "删除成功") : R.failed("删除失败");
    }


}
